package com.mr.web.controller;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.mr.util.StringUtil;
@Controller
public class UploadPictureController extends AnnotationController{
	@RequestMapping("/auth/public/uploadPicture.xhtml")
	public String uploadPicture(HttpServletRequest req, ModelMap model){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
		MultipartFile file = multipartRequest.getFile("userfile");
		String extname = StringUtil.getFilenameExtension(file.getOriginalFilename());
		if(!validPic(extname)) return showJsonFailure("图片不合法!", model);
		byte[] buffer = new byte[1024];
		int len = -1;
		try {
			InputStream in = file.getInputStream();
			String fileName = StringUtil.getNewFileName(file);
			String path = req.getSession().getServletContext().getRealPath("/upload/user") + "/" + fileName;
			OutputStream out = new FileOutputStream(path);
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			in.close();
			out.close();
			model.put("fileURL", "upload/user/"+fileName);
		} catch (Exception e) {
			e.printStackTrace();
			return showJsonFailure("上传失败", model);
		}
		return showJsonSuccess(model);
	}
}
